package com.pengtu.gsj.service.impl.check.yh.equipment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.pengtu.gsj.entity.app.Attachment;
import com.pengtu.gsj.entity.app.Organization;
import com.pengtu.gsj.entity.check.CheckTable;
import com.pengtu.gsj.service.check.CheckTableService;
import com.pengtu.gsj.service.check.DownService;
import com.pengtu.gsj.service.check.yh.equipment.MechanizationService;
import com.pengtu.gsj.service.system.OrganizationService;
import com.pengtu.gsj.service.system.SystemManageService;

@Service
@Transactional
public class MechanizationServiceImpl implements MechanizationService {

	@Autowired
	private CheckTableService checkTableService;
	@Autowired
	private SystemManageService systemManageService;
	@Autowired
	private DownService downService;
	@Autowired
	private OrganizationService organizationService;
	
	@Override
	public Map<String, Object> getCheckContent(String startTime,
			String endTime, CheckTable checkTable, String tag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Attachment> result = new ArrayList<Attachment>();
		List<Object> values = new ArrayList<Object>();
		
		JSONObject jsonObject = JSONObject.parseObject(checkTable.getRetrieval());
		double yearFull = Double.parseDouble((String)jsonObject.get("yearFull"));
		String orgId = (String)jsonObject.get("orgId");
		
		result = systemManageService.getCheckAttachments(startTime, endTime, tag);
		//根据orgId和时间 、标签查询是否有无附件 如果有  再将相关的附件加入到list中去
		List<Attachment> list = systemManageService.getCheckAttachmentsByPartId(startTime, endTime, tag, orgId);
		double total = 0; //检查得分
		double percentage = 0; //系统完善度
		double tableFull = yearFull*4;
		String orgName = "";
		if (StringUtils.isNotEmpty(orgId)) {
			if (list.size() > result.size()) {
				total = tableFull;
				percentage = 100.0;
				map.put("electronization", true);
			} else {
				total = 3*yearFull;
				percentage = 0;
				map.put("electronization", false);
			}
			values.add(orgId);
			Organization organization = organizationService.getOrganization(orgId);
			if (organization != null) {
				orgName = organization.getOrgName();
			}
			map.put("sum", total);
			map.put("percentage", percentage);
		} else {
			//判断是否有无检查单位
			map.put("electronization", false);
		}
		
		checkTableService.updateCheckTable(checkTable, percentage, total, tableFull, values);
		map.put("att", list);
		map.put("score", checkTable.getTestFull());
		map.put("checkTable", checkTable);
		map.put("orgName", orgName);
		return map;
	}
	
}
